from werkzeug.utils import secure_filename
from flask import Blueprint, request, current_app, make_response, send_from_directory
from lina.service.PhaseService import PhaseService
from lina.service.CaseService import CaseService
from lina.service.TagService import TagService
from lina.service.AttachmentService import AttachmentService
from lina.service.CommentService import CommentService


from lina.utils import response
import logging
import os
import time
import datetime
import random


class Pic_str:
    def create_uuid(self):  # 生成唯一的图片的名称字符串，防止图片显示时的重名问题
        nowTime = datetime.datetime.now().strftime("%Y%m%d%H%M%S")  # 生成当前时间
        randomNum = random.randint(0, 100)  # 生成的随机整数n，其中0<=n<=100
        if randomNum <= 10:
            randomNum = str(0) + str(randomNum)
        uniqueNum = str(nowTime) + str(randomNum)
        return uniqueNum


blueprint = Blueprint('mainpage', __name__)

logger = logging.getLogger('lina_console')

phaseService = PhaseService()
caseService = CaseService()
tagService = TagService()
attachmentService = AttachmentService()
commentService = CommentService()


@blueprint.route('/')
def index():
    return "Hello world"


@blueprint.route('/api/phase')
# 获取所有的列表
def get_phases():
    result = phaseService.get_all_phase()
    return response(result)


@blueprint.route('/api/tags')
# 获取所有标签
def fetch_all_tag():
    result = tagService.fetch_all()
    return response(result)


@blueprint.route('/api/fetch_cases_by_phase_ids', methods=['POST'])
# 获取[多个]列表中的案件
def fetch_cases_by_phase_ids():
    phase_ids = request.json['phase_ids']
    case_list = caseService.fetch_cases_by_phase_ids(phase_ids)
    return response(case_list)


@blueprint.route('/api/update_tag_by_case_id', methods=['POST'])
# 更新案件的所有标签
def update_tag_by_case_id():
    case_id = request.json['case_id']
    tags = request.json['tags']
    return response(caseService.update_tags_by_case_id(case_id, tags))


@blueprint.route('/api/fetch_comments_by_case_id/<case_id>', methods=['GET'])
# 获取案件的评论列表
def fetch_comments_by_case_id(case_id):
    result = commentService.fetch_comments_by_case_id(case_id)
    return response(result)


# 根据id查询一个案件的详细内容
@blueprint.route('/api/fetch_case_by_id/<case_id>', methods=['GET'])
def fetch_case_by_id(case_id):
    result = caseService.fetch_case_by_id(case_id)
    return response(result)


# 根据id查询一个案件的附件图片列表
@blueprint.route('/api/fetch_attachments_by_case_id/<case_id>', methods=['GET'])
def fetch_attachments_by_case_id(case_id):
    result = attachmentService.get_pic_by_case_id(case_id)
    return response(result)


# 查看图片
@blueprint.route('/api/show/<string:filename>', methods=['GET'])
def show_photo(filename):
    img_dir = current_app.config['IMG_FOLDER']
    if request.method == 'GET':
        if filename is None:
            pass
        else:
            image_data = open(os.path.join(img_dir, '%s' %
                                           filename), "rb").read()
            response = make_response(image_data)
            response.headers['Content-Type'] = 'image/png; image/jpeg'
            return response
    else:
        pass


# 上传案件的图片附件
@blueprint.route('/api/upload_pic', methods=['POST'])
def upload_pic():
    case_id = request.form['case_id']
    img_dir = current_app.config['IMG_FOLDER']

    if not os.path.exists(img_dir):
        os.makedirs(img_dir)
    f = request.files['file']
    if f and allowed_file(f.filename):
        fname = secure_filename(f.filename)
        ext = fname.rsplit('.', 1)[1]
        new_filename = Pic_str().create_uuid() + '.' + ext

        f.save(os.path.join(img_dir, new_filename))
        result = attachmentService.add_case_pic(case_id, new_filename)

        return response(result)


def allowed_file(filename):
    ALLOWED_EXTENSIONS = set(
        ['png', 'jpg', 'jpeg', 'JPG', 'PNG', 'gif', 'GIF'])
    return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
